package com.tju.ocean_ecology_website.security;

import com.tju.ocean_ecology_website.entity.User;
import com.tju.ocean_ecology_website.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户详情服务，用于加载用户信息
 */
@Service
public class JwtUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }
        
        // 根据用户角色设置权限
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        switch (user.getRole()) {
            case 0:
                authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
                break;
            case 1:
                authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
                break;
            case 2:
                authorities.add(new SimpleGrantedAuthority("ROLE_VOLUNTEER"));
                break;
            case 3:
                authorities.add(new SimpleGrantedAuthority("ROLE_ORGANIZATION"));
                break;
            default:
                authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        }
        
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(), user.getPassword(), authorities);
    }
}
